﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Text;
using Common;

public partial class tools_sysrightseditor : System.Web.UI.Page
{
    public string PageTitle = "";

    protected void Page_Load(object sender, EventArgs e)
    {
        Response.Expires = -1;

        //if (Profile.AccountInfo.UserName != "admin")
        //{
        //    Response.Redirect("../unauthorized.htm?errcode=5");
        //    Response.End();
        //}

        switch (RequestBase.GetFormString("otype"))
        {
            case "getfunctionlist":
                LoadFunctionDataList();
                break;
        }

        if (!IsPostBack)
        {
            DropdownListDataBind();

            if (RequestBase.GetQueryString("otype") == "modify")
            {
                Initialize();
                PageTitle = "修改权限";
            }

            if (RequestBase.GetQueryString("otype") == "add")
                PageTitle = "新增权限";
        }
    }

    #region 下拉菜单数据邦定
    void DropdownListDataBind()
    {
        DataTable dt = BLL.CommonBLL.Select(
            "System_FunctionCategory",
            "FunctionCategoryId, CategoryName",
            " ORDER BY LineNum ASC");
        
        foreach (DataRow dr in dt.Select(""))
        {
            drplCategories.Items.Add(new ListItem(dr["CategoryName"].ToString().Trim(), dr["FunctionCategoryId"].ToString().Trim()));
        }
        dt.Dispose();

        drplCategories.Attributes.Add("onchange", "LoadFunctionDataList();");
    }
    /// <summary>
    /// 获取子类明细
    /// </summary>
    void LoadFunctionDataList()
    {
        string categoryid = RequestBase.GetFormString("categoryid");
        StringBuilder selOptions = new StringBuilder();
        string items = "<option value=\"{0}\">{1}</option>";

        DataTable dat = BLL.CommonBLL.Select("vw_SystemFunctions", "[FunctionId], [FunctionName]", " AND FunctionCategoryId = '" + RequestBase.GetFormString("categoryid") + "' ORDER BY LineNum ASC");
        selOptions.Append(string.Format(items, "", "-- 请选择所属模块 --"));
        foreach (DataRow dr in dat.Select(""))
        {
            selOptions.Append(string.Format(items, dr["FunctionId"].ToString(), dr["FunctionName"].ToString()));
        }

        dat.Clear();
        dat.Dispose();
        BLL.AjaxHelper.ResponseWrite(selOptions.ToString());
    }
    #endregion

    #region 数据初始化
    /// <summary>
    /// 数据邦定
    /// </summary>
    void Initialize()
    {
        if (RequestBase.GetQueryString("privilegeid") != "")
        {
            DataTable dt = BLL.CommonBLL.Select("vw_SystemPrivileges", "*", " AND PrivilegeId = '" + RequestBase.GetQueryString("privilegeid").Trim() + "'", "");
            if (dt.Rows.Count > 0)
            {
                txtRightsName.Text = dt.Rows[0]["PrivilegeName"].ToString().Trim();
                txtFunctionId.Value = dt.Rows[0]["FunctionId"].ToString().Trim();
                txtLowerName.Text = dt.Rows[0]["LoweredPrivilegeName"].ToString().Trim();
                drplCategories.SelectedValue = dt.Rows[0]["FunctionCategoryId"].ToString();
                rbltCanBeDeep.SelectedValue = (dt.Rows[0]["CanBeDeep"].ToString().ToLower().Trim() == "true") ? "1" : "0";
                txtOriginalLowerName.Value = dt.Rows[0]["LoweredPrivilegeName"].ToString().Trim();
                txtLineNum.Text = dt.Rows[0]["LineNum"].ToString().Trim();
            }
            dt.Dispose();
        }
    }
    #endregion

    #region 保存数据
    protected void butBegin_ServerClick(object sender, EventArgs e)
    {
        string result = "";
        string SQL = "";
        ///添加模式
        if (RequestBase.GetQueryString("otype") == "add")
        {
            SQL = "INSERT System_FunctionPrivilegeBase Values(NEWID(), '" + txtFunctionId.Value.Trim() + "', '" + txtRightsName.Text.Trim() + "','" + txtLowerName.Text.Trim().ToLower() + "', " + BuildLineNum(txtFunctionId.Value.Trim(), "{00000000-0000-0000-0000-000000000000}") + ", " + rbltCanBeDeep.SelectedValue.Trim() + ", '')";
            try
            {
                DBUtility.SqlHelper.ExecuteNonQuery(DBUtility.SqlHelper.ConnectionStringMembership, CommandType.Text, SQL, null);
                result = "权限添加成功!";
            }
            catch (Exception err)
            {
                JScript.Alert(err.ToString());
                return;
            }
        }

        ///修改模式
        if (RequestBase.GetQueryString("otype") == "modify" && RequestBase.GetQueryString("privilegeid") != "")
        {
            SQL = "UPDATE System_FunctionPrivilegeBase SET FunctionId = '" + txtFunctionId.Value.Trim() + "', PrivilegeName = '" + txtRightsName.Text.Trim() + "', LoweredPrivilegeName = '" + txtLowerName.Text.Trim().ToLower() + "', CanBeDeep = " + rbltCanBeDeep.SelectedValue.Trim() + " WHERE PrivilegeId = '" + RequestBase.GetQueryString("privilegeid").Trim() + "'";
            try
            {
                DBUtility.SqlHelper.ExecuteNonQuery(DBUtility.SqlHelper.ConnectionStringMembership, CommandType.Text, SQL, null);
                result = "权限修改成功!";
            }
            catch (Exception err)
            {
                JScript.Alert(err.ToString());
                return;
            }
        }

        JScript.AlertAndReturnValueToParent(result, "window.dialogArguments.document.getElementById(\"RefreshItems\").click(); window.close();");
    }
    /// <summary>
    /// 生成模块权限编码
    /// </summary>
    private static int BuildLineNum(string functionId, string privilegeid)
    {
        int linenum = 0;
        object obj = BLL.CommonBLL.ExecuteScalar("System_FunctionPrivilegeBase", "Max(LineNum)", " AND FunctionId = '" + functionId + "' AND PrivilegeId <> '" + privilegeid + "'", true);
        if (string.IsNullOrEmpty(obj.ToString()) || obj == null)
            linenum = 1;
        else
            linenum = (int)obj + 1;
        return linenum;
    }
    #endregion
}
